package com.itheima.Demo;

import java.util.Arrays;
import java.util.Collections;

public class Demo二分查找 {
    public static void main(String[] args) {
        //准备数组
        int[] arr = {23,535,56,864,32,98,452,13,5,8};

        int i = find(arr, 5);
        System.out.println(i);
        System.out.println(Arrays.toString(arr));

    }
    //二分查找


    //比较
    //代表要找的值正好就是中间值
    public static int find(int[] arr, int num) {
        Arrays.sort(arr);

        //定义头尾
        int start = 0;
        int end = arr.length - 1;
        //循环结束判断
        while (true) {
            if (start > end) {
                return -1;//代表找不到
                //定义中间索引
            }
            int mid = (start + end) / 2;
            if (num < arr[mid]) {
                end = mid - 1;
            } else if (num > arr[mid]) {
                start = mid + 1;
            } else {
                return mid;
            }
        }
    }
}
